from scitk.widgets.tkgraph.graph import Graph
import tkinter as tk
from tkinter import ttk
from scitk.widgets.tkwidgetext.closablenotebook import ClosableNotebook


class PlotNoteBook(ClosableNotebook):
    def __init__(self, parent):
        super().__init__(parent)
        # self.pack(expand = True, fill = tk.BOTH)

    def on_idle(self, event):
        for i in range(self.GetPageCount()):
            title = self.GetPage(i).title
            if self.GetPageText(i) != title:
                self.SetPageText(i, title)

    def figure(self, i=None):
        return self.get_tab(i)

    def set_background(self, img):
        self.GetAuiManager().SetArtProvider(ImgArtProvider(img))

    def add_figure(self, figure=None, name='unnamed'):
        if figure is None:
            return  # grid =MGrid(self)
        self.add_tab(figure, text=name)
        return figure

    def set_title(self, panel, title):
        self.SetPageText(self.GetPageIndex(panel), title)

    def on_valid(self, event):
        pass

    def on_close(self, event):
        pass

    def mpl_connect(self, evt, method):
        if self.figure() is None: return
        self.figure().mpl_connect(
            'motion_notify_event', self.mouse_move)


class TKGraphNoteFrame(ttk.Frame):
    def __init__(self, parent, toolbar=True):
        super().__init__(parent)
        self.notebook = PlotNoteBook(self)
        # self.figure = self.notebook.figure
        self.add_figure = self.notebook.add_figure
        self.notebook.pack(expand=True, fill=tk.BOTH)
        self.pack(expand=True, fill=tk.BOTH)

    # def add_toolbar(self):
    #     self.toolbar = NavigationToolbar(self.notebook)
    #     self.toolbar.Realize()
    #     self.GetSizer().Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
    #     self.toolbar.update()

    def add_plot(self, x: list, y: list, x_tick=-1, y_tick=-1, color='black', linecolor='', markercolor='',
                 showline=True, showmarker=True, markersize=5, name='unnamed'):
        '''
        新建一个标签页，并且在这个标签页上面进行绘图操作。无需手动设置范围，因为是自适应的。
        输入参数：
            x:列表，比如[1,2,3]
            y:列表，比如[1,2,3]
            color:字符串，比如'black'。决定线条和标记的颜色。
            linecolor:字符串。决定线条颜色
            markercolor:字符串，决定标记的颜色
            showline:bool型，默认为True。决定线段颜色。
            showmarker:bool型，默认为True。决定点的颜色。
            markersize:int型，代表圆点的半径，单位是像素。它默认为5。
            注意：如果show_line和show_marker都是False的话，将不会显示任何内容。
            局限性：请注意，你不能改变散点的形状。
        '''
        g = Graph(self,height = 500,width=400)

        g.plot(x, y, color=color, linecolor=linecolor, markercolor=markercolor, markersize=markersize,
                showline=showline, showmarker=showmarker,xyautofit=True)
        self.notebook.add_figure(g, name=name)


    def create_figure(self):
        '''
        create a new figure in a new tab, return a new figure for plot.
        新建一个标签页，并且在其上创建一个新的figure。返回值为plt.figure。
        '''
        pframe = Graph(self)
        self.notebook.add_figure(pframe)
        return pframe

    def clear_figure(self, tab_id: int) -> None:
        '''
        clear all plots on tab identified by tab_id.
        清空tab_id所对应的标签页上的图像。
        '''
        f = self.get_figure(tab_id).clf()

    def get_figure_tab(self, tab_id: int) -> Graph:
        """获取tab_id对应的figure的标签页。"""
        return self.notebook.get_tab(tab_id)

    def get_figure(self, fig_id=None) -> Graph:
        '''获取当前fig_id对应的Figure.在tkintergraph中，figure就是figure_tab，亦即Graph类。'''
        return self.get_figure_tab(tab_id=fig_id)

    def delete_figure(self, tab_id: int):
        """
        delete figure tab identified by tab_id.
        删除tab_id表示的标签页及其上的图像。
        """
        self.notebook.delete_tab(tab_id)

    def update(self, tab_id=None):
        '''
        update figure identified by tab_id
        刷新tab_id对应的标签页的Figure，当清除重绘的时候应当调用此函数。
        '''
        canvas = self.get_figure_tab(0).figure
        canvas.draw()
        canvas.flush_events()


if __name__ == '__main__':
    import numpy as np

    app = tk.Tk()
    pnf = TKGraphNoteFrame(app)
    pnf.add_plot([1, 2, 3], [1, 2, 3], linecolor='red', markersize=10, name='hhhhhh')
    pnf.add_plot([1, 4, 3], [1, 2, 3], linecolor='red', markersize=10)
    pnf.add_plot([1, 6, 3], [1, 2, 3], linecolor='red', markersize=10)
    pnf.add_plot([1, 9, 3], [1, 2, 3], linecolor='red', markersize=10)

    figure = pnf.get_figure(3)
    figure.draw_axes()
    figure.plot(np.array([1, 2, 3, 4, 5, 6, 7]), np.array([3, 4, 5, 6, 7, 8, 9]) * 3 / 9)  # 获取图像figure_tab，并且在其上画图。

    app.mainloop()
